#! /usr/bin/env python

from bs4 import BeautifulSoup
import re
import sys
import os

#passive_error_list = ['3174','3005','3028','3186','3126','3004','3089','3141','3072','3134','3077','3142']
filename=sys.argv[1]

soup = BeautifulSoup(open(filename))
#print soup.prettify()
tagtags = soup.find_all('table',{ 'class':'champion_item'})

blipp = sys.argv[2]

ITEMIDS=[]
print "import operator"
print "import copy"
print ""

#for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_%s' % (blipp))}):
for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_\d+')}):
    #    print tag.prettify()
    itemid=tag['id'][-4:]
    ITEMIDS.append(itemid)
    name=tag.h1.string
    itemname = name
    desc=tag.p.string
#    print "[%s]" % (itemid)
#    print "name = %s" %(name)
#    print "!desc!%s!" % (desc)
    # desc processing
    desc_stats = ""
    #desc_type = ""
    active_stats = ""
    passive_stats = ""
    chunks = []
    rx = re.search('(Active|Passive|Aura)',desc) #regex 0
    if rx:
#        print "regex 0 match" # debug
#        desc_type = rx.group(1)
        m = re.match('([a-zA-Z0-9+% \.]+)(UNIQUE|Active|Passive|Aura)',desc) #regex 1
        if not m:
#            print "regex NOT match #1" #debug
            if re.match('(UNIQUE|Active|Passive|Aura)',desc): #regex 2
#                print "yeah"
                desc_stats = desc
                desc_stats = re.sub('UNIQUE','',desc_stats)
                chunks  = re.split('(Active|Passive|Aura)',desc_stats)
                desc_stats = ""
#                print chunks #debug
            else:
#                print "regex match #2" # debug
                desc_stats = desc
                print "ERROR_1 = True"
        else:
#            print "regex 1 match" # debug
            desc_stats = m.group(1)
#             print "!!!",desc_stats,"!" # debug
            desc_stats = re.sub('UNIQUE','',desc_stats)
            chunks  = re.split('(Active|Passive|Aura)',desc)
            chunks.pop(0)
            
        for i in range(0,len(chunks)):
            chunk = re.sub('UNIQUE','',chunks[i])
            chunk = re.sub('^:\s?','',chunk)
            if chunk == "Active":
                temp = re.sub('UNIQUE','',chunks[i+1])
                temp = re.sub('^:\s?','',temp)
                active_stats += temp.rstrip(' ') +";"
                i += 2
                continue
            if chunk == "Passive":
                temp = re.sub('UNIQUE','',chunks[i+1])
                temp = re.sub('^:\s?','',temp)
                temp = temp.rstrip(' ')
#                print "!temp!%s!" % (temp) # debug
                if "Enhanced Movement 2" in temp:
#                    passive_stats += temp.rstrip(' ') +";"
#                    print "!!!!!!!!!!!",temp 
#                    print "Movement Speed = 20"
                    desc_stats += "+70 Movement Speed "
                    passive_stats += "+70 Movement Speed;"
                    
                    i += 2
                if "Enhanced Movement 1" in temp:
#                    passive_stats += temp.rstrip(' ') +";"
#                    print "!!!!!!!!!!!",temp 
#                    print "Movement Speed = 20"
                    desc_stats += "+50 Movement Speed "
                    passive_stats += "+50 Movement Speed;"
                    
                    i += 2
                if "Enhanced Movement 3" in temp:
#                    passive_stats += temp.rstrip(' ') +";"
#                    print "!!!!!!!!!!!",temp 
#                    print "Movement Speed = 20"
                    desc_stats += "+90 Movement Speed "
                    passive_stats += "+90 Movement Speed;"
                    
                    i += 2

                    
                else:
                    if re.match('\+([0-9.]+?%?)\s+?(.+)$',temp):
                        desc_stats +=  temp.rstrip(' ')
                        passive_stats += temp.rstrip(' ') +";"
                    elif re.match('([0-9.]+?%)\s+?Cooldown Reduction',temp):
                        desc_stats += "+%s" %(temp.rstrip(' '))
                        passive_stats += "+%s" %(temp.rstrip(' ')) +";"
                    else:
                        passive_stats += temp.rstrip(' ') +";"
                    i += 2
                continue

    elif re.search('Click to Consume',desc):
#        print "ERROR = True"
        pass
    else:
        desc_stats = desc


#    print desc_stats
#    print "!!!!!!!",desc_stats,"!!"
    class_string = ""
    chunks = desc_stats.split('+')

    for chunk in chunks:
        chunk = chunk.rstrip(' ')
#        print "!chunk!",chunk,"" #debug
        if chunk == "" or re.search('^\s+$',chunk):
            continue
#        print "!chunk!",chunk,"!!"
        m = re.match('([0-9.]+?%?)\s+?(.+)$',chunk)
        if m:
 #           print  m.group(2) + " = " + m.group(1)
            class_string += "%s,%s;" %(m.group(2),m.group(1))
        else:
            print "Regex Error"
            print "RegexError-desc_stats!",desc_stats,"!"

    #create_class(itemid,class_string.rstrip(';'),itemname)


    print "class Item_%s():" % (itemid)
    print "    def __init__(self):"
    print "        self.parent=False"
    print "        self.Name=\"%s\"" % (itemname)
    print "        self.Icon=\"%s.png\"" % (itemid)
    print "        self.ID=%s" % (itemid)
    print "        self.Stack=0"
    print "        self.MaxStack=0"
    
    if tag.table == None:
        print "        self.Built_From=[]"
    else:
        imgs = tag.table.find_all('img')
        imgs.pop(0)
        builtfrom = ""
        for i in imgs:
            builtfrom += i['src'][-8:-4] + ","

        tempstring=builtfrom.rstrip(',')
        tempstring=re.sub(',',"','",tempstring)
        print "        self.Built_From=['%s']" %(tempstring)

    buildsintodiv = tag.find('div',{'class':'item_parents'})
    if buildsintodiv == None:
        print "        self.Builds_Into=[]"
    else:
        buildsinto = ""
        for i in buildsintodiv.find_all('img'):
            buildsinto += i['src'][-8:-4] + ","

        tempstring=buildsinto.rstrip(',')
        tempstring=re.sub(',',"','",tempstring)
        print "        self.Builds_Into=['%s']" %(tempstring)

#tags 
        
#<a class="lol_item" href="/items#3172" style="text-decoration: none;">
#<span class="highlight">Cloak and Dagger</span><br/>
#</a>
#<p>+20% Attack Speed +20% Critical Strike Chance  UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)</p>
#    <div class="item_geneology left  filter_tag_critical_strike filter_tag_attack_speed"
#
    for xx in tagtags:
        for td in xx.find_all('td'):
            if td['class'][0] == "item_icon":
                if itemid in td.a.attrs['href']:
#                    print xx.prettify()
                    string = ""
                    for x in xx.find_all('div',{'class':'item_geneology'}):

                        if x.attrs['class'][1] == 'left':
                            #string = ""
                            for i in x.attrs['class']:
                                if 'filter' in i:
                                    string += i[11:] + ","
                    if len(string) == 0:
                        if itemid == "3200":
                            print "        self.Tags=['spell_damage','viktor']"
                        elif itemid == "3198":
                            print "        self.Tags=['spell_damage','viktor']"
                        elif itemid == "3197":
                            print "        self.Tags=['spell_damage','mana','cooldown_reduction','viktor']"
                        elif itemid == "3196":
                            print "        self.Tags=['spell_damage','health','health_regen','movement','viktor']"
                        elif itemid == "1055":
                            print "        self.Tags=['health','attack_speed','life_steal','doran']"
                        elif itemid == "1056":
                            print "        self.Tags=['health','spell_damage','mana_regen','doran']"
                        elif itemid == "1054":
                            print "        self.Tags=['health','armor','health_regen','doran']"
                        elif itemid == "1055":
                            print "        self.Tags=['health','attack_speed','life_steal','doran']"
                        elif itemid == "2003":
                            print "        self.Tags=['health','consumeable']"
                            active_stats = "yes"
                        elif itemid == "2004":
                            print "        self.Tags=['mana','consumeable']"
                            active_stats = "yes"
                        elif itemid == "2038":
                            print "        self.Tags=['attack_speed','critical_strike','consumeable']"
                            active_stats = "yes"
                        elif itemid == "2039":
                            print "        self.Tags=['spell_damage','cooldown_reduction','consumeable']"
                            active_stats = "yes"
                        elif itemid == "2037":
                            print "        self.Tags=['health','damage','consumeable']"
                            active_stats = "yes"
                        elif itemid == "2042":
                            print "        self.Tags=['consumeable']"
                            active_stats = "yes"
                        elif itemid == "2043":
                            print "        self.Tags=['consumeable']"
                            active_stats = "yes"
                        elif itemid == "2047":
                            print "        self.Tags=['consumeable']"
                            active_stats = "yes"
                        elif itemid == "1062":
                            print "        self.Tags=['health','damage','life_steal','prospector']"
                            active_stats = "yes"
                        elif itemid == "1063":
                            print "        self.Tags=['spell_damage','mana_regen','health','prospector']"
                            active_stats = "yes"
                        elif itemid == "2044":
                            print "        self.Tags=['consumeable']"
                            active_stats = "yes"

                        else:
                            print "        self.Tags=[]"
                            print "ERROR_TAGS = True"
                    else:
                        string = string.rstrip(',')
                        string=re.sub(',',"','",string)
                        print "        self.Tags=['%s']" % (string)
                    yy = xx.find('td',{'class':'cost'})
                    if yy:
                        m = re.search('>(\d+)<br',str(yy.span))
                        print "        self.Costs =",m.group(1)
                        m = re.search('br/>(\d+)</spa',str(yy.span))
                        print "        self.Total_Costs =",m.group(1)

#Builds from
#     <table class="item_tree item_tree_root" style="width: 184px;">
# Built into
#<div class="item_parents">""
    #output

    #print "default_description = %s" % (desc)
    print "        self.Description=\"%s\""  % (desc)
    print "        self.RichText_Description=\"\""
    if active_stats == "":
        print "        self.has_active=False"
    else:
        print "        self.has_active=True"
    if passive_stats == "":
        print "        self.has_passive=False"
    else:
        print "        self.has_passive=True"
    print "        self.Custom()"
    print ""

    print "    def UpdateStats(self):"

    string = class_string.rstrip(';')
    if len(string) == 0:
        print "        pass"
    else:
        for i in string.split(';'):
            if "Augment" in i:
                i="Augment,666"
            if "Tenacity (" in i:
                i="Tenacity,True"
            name,value = i.split(',')
            name = re.sub('\s+?',"_",name)
            if itemid == "3200":
                print "        self.parent.Ability_Power += 3.0 * self.parent.Level"
            elif itemid == "3156":
                print "        self.parent.Attack_Damage += 55.0"
                print "        self.parent.Magic_Resist += 36.0"
                print "        #self.parent.Attack_Damage += maxhealth - health = temp   (maxhelth/temp)*100 = temp  abs(temp/2.5)   _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0"
            elif "Pros" in name:
                print "        self.parent.Health += 200"
            elif "True" in value:
                print "        self.parent.%s=True" % (name)
            elif "." in value:
                print "        self.parent.%s += %s" % (name,value.rstrip('%'))
            else:
                print "        self.parent.%s += %s.0" % (name,value.rstrip('%'))
            if "%" in value:
                print "        # above is %"
        print "        self.UpdateStats_Custom()"
        print ""
    if os.path.isfile("Custom/%s.py" % (itemid)):
        FILE=open("Custom/%s.py" % (itemid),'r')
        for i in FILE.readlines():
            print i.rstrip()
        print ""
        print ""
    else:
        print ""
        print "    def Custom(self):"
        print "        pass"
        print ""
        print "    def UpdateStats_Custom(self):"
        print "        pass"

        print ""
        print ""


print """
class Items():
    def __init__(self,parent):
        self.parent=parent
        self.ITEMS={}
        self.InitItems()"""

string = "['"
for i in ITEMIDS:
    string += i + "','" 

string=string[:-2] + "]"
print "        self.ItemIndex=%s" % (string)
print "        self.CreateLists()"
print """
    def InitItems(self):"""
for i in ITEMIDS:
    print "        self.ITEMS['%s']=Item_%s()" % (i,i)

print """
    def GetItem(self,itemid):
        return self.ITEMS[str(itemid)]

    def GetItemCopy(self,itemid):
        return copy.deepcopy(self.ITEMS[str(itemid)])

    def CreateLists(self):
        self.SortedLists={}
        for ItemID in self.ItemIndex:
            for i in self.ITEMS[ItemID].Tags:
                if not self.SortedLists.has_key(i):
                    self.SortedLists[i]=[]
                    self.SortedLists[i].append(ItemID)
                else:
                    self.SortedLists[i].append(ItemID)
        for i in self.SortedLists:
            costs = {}
            for j in self.SortedLists[i]:
                costs[j] = self.ITEMS[j].Total_Costs
            self.SortedLists[i] = []
            for k,l in sorted(costs.iteritems(), key=operator.itemgetter(1)):
                self.SortedLists[i].append(k)
            


    def GetList(self,string):
#attack_speed
#doran
#life_steal
#spell_damage
#viktor
#armor
#spell_block
#damage
#health_regen
#mana
#health
#consumeable
#movement
#mana_regen
#critical_strike
#prospector
#cooldown_reduction
        return self.SortedLists[string]

"""
